import os
import time
import logging
from datetime import datetime
from config import ALERT_COOLDOWN, ALERT_LOG_FILE
from utils.phone_alert import PhoneAlertService

class AlertSystem:
    def __init__(self):
        self.last_alert_time = {}
        self.setup_logging()
        self.phone_alert = PhoneAlertService()

    def setup_logging(self):
        """设置日志系统"""
        log_dir = os.path.dirname(ALERT_LOG_FILE)
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

        logging.basicConfig(
            filename=ALERT_LOG_FILE,
            level=logging.INFO,
            format='%(asctime)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )

    def trigger_alert(self, alert_type):
        """触发报警"""
        current_time = time.time()
        
        # 检查是否在冷却时间内
        if alert_type in self.last_alert_time:
            time_since_last = current_time - self.last_alert_time[alert_type]
            if time_since_last < ALERT_COOLDOWN:
                return

        # 记录报警时间
        self.last_alert_time[alert_type] = current_time

        # 记录报警日志
        logging.info(f'警报: {alert_type}')
        print(f'\n[警报] {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} - {alert_type}')
        
        # 发送电话预警
        self.phone_alert.make_voice_call(alert_type)

    def get_alert_history(self):
        """获取报警历史记录"""
        if not os.path.exists(ALERT_LOG_FILE):
            return []

        with open(ALERT_LOG_FILE, 'r', encoding='utf-8') as f:
            return f.readlines()